﻿{extend name="public:base" /}

{block name="css"}
<style>
.truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 200px;
}
.video-preview {
    min-width: 200px;
}
</style>
{/block}

{block name="content"}
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <a href="{:url('doVideo')}" class="btn btn-primary btn-lg">新增</a>
                    {if input('meal_id') > 0}
                    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">排序</button>
                    {/if}
                    <div class="ibox-tools">
                        <a class="collapse-link">
                            <i class="iconfont icon-chevron-up"></i>
                        </a>
                    </div>
                </div>

                <div class="ibox-content">
                    <div class="row search-form">
                        <div class="col-sm-2 m-b-sm">
                            <div class="input-group">
                                <select name="meal_id" class="form-control form-control-lg">
                                    <option value="0">请选择套餐</option>
                                    {volist name="meal_list" id="vo"}
                                    <option value="{$vo.id}" {$vo.id == input('meal_id') ? 'selected' : ''}>{$vo.name}</option>
                                    {/volist}
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-2 m-b-sm">
                            <div class="input-group">
                                <select name="status" class="form-control form-control-lg">
                                    <option value="0">请选择状态</option>
                                    <option value="1" {:input('status') == 1 ? 'selected' : ''}>启用</option>
                                    <option value="-1" {:input('status') == -1 ?  'selected' : ''}>禁用</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-2 m-b-sm">
                            <div class="input-group">
                                <button type="button" class="btn btn-primary btn-lg screen-btn">搜索</button>
                            </div>
                        </div>
                    </div>

                    <div class="hr-line-dashed"></div>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <tr>
                                <th>ID</th>
                                <th>视频</th>
                                <th>名称</th>
                                <th>虚拟点赞数</th>
                                <th>真实点赞数</th>
                                <th>状态</th>
                                <th>转换状态</th>
                                <th>操作</th>
                            </tr>
                            {volist name="list" id="vo"}
                            <tr>
                                <td>{$vo.id}</td>
                                <td>
                                    <div class="video-preview">
                                        <!-- 视频预览播放器 -->
                                        <video id="video-{$vo.id}" controls style="max-width: 200px; max-height: 150px;"></video>
                                        <!-- 视频路径 -->
                                        <div class="video-path text-muted text-xs mt-1 truncate" title="{$vo.path}"></div>
                                    </div>
                                </td>
                                <td>{$vo.name}</td>
                                <td>{$vo.zan_count}</td>
                                <td>{$vo.user_zan_count}</td>
                                <td>{$vo.status == 1 ? '启用' : '禁用'}</td>
                                <td>
                                    {if condition="$vo.convert_status == 1"}
                                    <span class="label label-warning">处理中</span>
                                    {elseif condition="$vo.convert_status == 2" /}
                                    <span class="label label-primary">处理完成</span>
                                    {elseif condition="$vo.convert_status == 3" /}
                                    <span class="label label-danger">处理失败</span>
                                    {else /}
                                    <span class="label label-default">未知</span>
                                    {/if}
                                </td>
                                <td>
                                    <a href="{:url(doVideo, ['id' => $vo.id])}" class="btn btn-white btn-sm"><i class="iconfont icon-edit"></i> 编辑 </a>
                                    <a href="{:url(delVideo, ['id' => $vo.id])}" class="btn btn-white btn-sm ajax-del"><i class="iconfont icon-trash"></i> 删除
                                    </a>
                                </td>
                            </tr>
                            {/volist}
                        </table>
                        {if !empty($list)}{$list->render()}{/if}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated flipInY">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">排序</h4>
            </div>
            <div class="modal-body">
                <div id="list">
                    {volist name="list" id="vo"}
                    <div data-id="{$vo.id}">{$vo.name}</div>
                    {/volist}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveSort()">更新排序</button>
            </div>
        </div>
    </div>
</div>
{/block}

{block name='js'}
<script src="__STATIC__/layui/layui.js"></script>
<!-- 引入HLS播放器库，用于播放M3U8格式视频 -->
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.4.12/dist/hls.min.js"></script>
<script src="__ADMIN__/js/Sortable.js"></script>
<script>
    (function () {
        //文字拖拽
        Sortable.create(document.getElementById('list'), {
            animation: 150,
            //onAdd,onUpdate,onRemove,onStart,onSort,onEnd
            onUpdate: function (evt){
                var oldIndex = evt.oldIndex;
                var newIndex = evt.newIndex;
                console.log(oldIndex);
                console.log(newIndex)
            }
        });
    })();

    /**
     * 更新排序
     * */
    function saveSort()
    {
        var divObj = $('#list > div');
        if(divObj.length > 0){
            var sortObj = [];
            divObj.each(function (index, val){
                var id = val.dataset.id;

                var sortObjSingle = {};
                sortObjSingle.id = id;
                sortObjSingle.sort = index;
                sortObj[index] = sortObjSingle;
            })
            var url = "/admin/manage/sortVideo";

            $.post(url, {
                sortObj: JSON.stringify(sortObj)
            }, function (res){
                if(res.result == 1){
                    layer.msg(res.msg);
                    setTimeout(function (){
                        window.location.href = window.location.href
                    },res.timer)
                }else{
                    layer.msg(res.msg)
                }
            },'json')
        }
    }
</script>
<script>
    // 初始化所有视频播放器
    $(function() {
        // 遍历所有视频预览元素
        $(document).find('.video-preview').each(function() {
            var videoElement = $(this).find('video')[0];
            if (videoElement) {
                // 从视频元素的ID获取视频ID
                var videoId = videoElement.id.replace('video-', '');
                // 获取视频路径
                var videoPath = $(this).find('.video-path').attr('title');
                if (videoPath) {
                    initVideoPlayer(videoId, videoPath);
                }
            }
        });
    });
    
    /**
     * 初始化视频播放器
     * @param {string} videoId 视频ID
     * @param {string} videoPath 视频路径
     */
    function initVideoPlayer(videoId, videoPath) {
        var videoElement = document.getElementById('video-' + videoId);
        if (!videoElement) return;
        
        // 检查视频路径是否为M3U8格式
        if (videoPath.endsWith('.m3u8')) {
            // 处理M3U8格式视频
            if (Hls.isSupported()) {
                var hls = new Hls();
                hls.loadSource(videoPath);
                hls.attachMedia(videoElement);
                hls.on(Hls.Events.MANIFEST_PARSED, function() {
                    console.log('M3U8文件解析完成，准备播放视频ID:', videoId);
                });
                hls.on(Hls.Events.ERROR, function(event, data) {
                    console.error('HLS播放错误:', data);
                    // 出错时尝试作为普通视频播放
                    try {
                        videoElement.src = videoPath;
                    } catch (e) {
                        console.error('无法播放M3U8视频:', videoId, e);
                    }
                });
            } else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
                // 如果浏览器原生支持HLS
                videoElement.src = videoPath;
                videoElement.addEventListener('loadedmetadata', function() {
                    console.log('原生HLS播放准备就绪:', videoId);
                });
            } else {
                // 不支持HLS，显示无法播放
                console.warn('浏览器不支持HLS播放:', videoId);
                videoElement.placeholder = '该浏览器不支持M3U8格式播放';
            }
        } else {
            // 处理MP4等普通视频格式
            videoElement.src = videoPath;
            videoElement.addEventListener('loadedmetadata', function() {
                console.log('普通视频加载完成:', videoId);
            });
        }
        
        // 视频错误处理
        videoElement.addEventListener('error', function() {
            console.error('视频播放错误:', videoId, videoElement.error);
        });
    }
</script>
{/block}